﻿using EasyNetQ;
using Kernel.Buildin.Service;
using Kernel.Command.Core;
using Kernel.Core.RabbitmqService;
using Kernel.Core.RabbitmqService.Options;

namespace WebAPI.Configure;

public static class RabbitMQExtensions
{
    public static void AddBuildinRabbitMQ(this IServiceCollection services, IConfiguration configuration)
    {
        if (Convert.ToBoolean(configuration.GetSection("RabbitMQ:Enabled").Value))
        {
            AnsiConsole.Markup("[darkcyan]RabbitMQ[/] is [yellow]Enabled[/]");
            services.AddRabbitmqPublisher();
            services.AddHostedService<HandlingHostedService>();

            //注册IBus为单例模式
            var provider = services.BuildServiceProvider();
            var options = provider.GetRequiredService<IOptions<RabbitmqPublisherOption>>().Value;
            services.AddSingleton(RabbitHutch.CreateBus($"host={options.HostName}:{options.Port};virtualHost={options.VirtualHosts};username={options.UserName};password={options.Password}"));
        }
        else
            AnsiConsole.Markup("[darkcyan]RabbitMQ[/] is [yellow]Disabled[/]");

    }

    public static IApplicationBuilder UseBuildinSubscribe(this IApplicationBuilder app, IConfiguration configuration)
    {
        if (Convert.ToBoolean(configuration.GetSection("RabbitMQ:Enabled").Value))
            app.UseBuildinSubscribe(Env.Current.KERNEL_SERVICE_NAME, typeof(Kernel.Service.Empty).Assembly);

        return app;
    }
}

